package org.sepheriel.airy2d.tiles;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import org.sepheriel.airy2d.math.QuadTree;
import org.sepheriel.airy2d.math.Vec2;
import org.sepheriel.airy2d.physic.Rectangle;
import org.sepheriel.airy2d.screen.Camera;
import org.sepheriel.airy2d.screen.Image;

/**
 * This Class represents the World in a Tile Based 2D Game.
 * This Class saves the layers and size of the World.
 * The World is saved in a QuadTree for better performance.
 * @author Sepheriel - Sascha Fitz
 */
public class TileWorld {

	int layers;
	int size;
	TileManager ressource;
	QuadTree world;
	
	Tile[][][] layer;
	
	/**
	 * TileWord Construct0r
	 * @param l the amount of layers of the World.
	 * @param size is the size of the World, this manipulates each layer.
	 */
	public TileWorld(int _layer, int _size) {
		this.ressource = new TileManager();
		size = _size;
		layer = new Tile[_layer][size][size];
		this.world = new QuadTree(new Rectangle(new Vec2(), 4096, 4096));
		
		for(int i = 0; i < _layer; i++)
		{
			for(int s = 0; s < this.size; s++) {
				for(int b = 0; b < this.size; b++) {
					layer[i][s][b] = new Tile(1);
					layer[i][s][b].calcPos(new Vec2(s, b));
				}
			}
		}
			
			for(int s = 0; s < this.size; s++) {
				for(int b = 0; b < this.size; b++) {
					world.insertTile(layer[0][s][b]);
				}
			}
			
			//---DEBUG---//

			/*Rectangle temp1 = new Rectangle(new Vec2(0,0), 100, 100);
			Rectangle temp2 = new Rectangle(new Vec2(10,10), 10, 10);
			Rectangle temp3 = new Rectangle(new Vec2(110,110), 100, 100);
			Rectangle temp4 = new Rectangle(new Vec2(50,50), 100, 100);
			
			System.out.println(temp1.overlap(temp2));
			System.out.println(temp2.overlap(temp1));
			
			System.out.println(temp1.overlap(temp4));
			System.out.println(temp4.overlap(temp1));
			
			System.out.println(temp3.overlap(temp1));
			System.out.println(temp4.overlap(temp2));*/
	}
	
	/**
	 * This method renders all Tiles "seen" by the Camera.
	 * The searching is done in a QuadTree for better performance.
	 * Includes Ambience Occlusion Mapping.
	 * @param cam is the cam of which parts of the World are seen.
	 */
	public void render(Camera cam) {
		
		List renderTiles = new ArrayList();
		
				//System.out.println(cam.getViewport().toString());
		world.findTiles(cam.getViewport(), renderTiles);
				//System.out.println(view.toString());
				//System.out.println(renderTiles.size());
		for(Object currTile: renderTiles) {
				//System.out.println(currTile);
			Image tile = ressource.textures.get(((Tile)currTile).getKind());
			Vec2 pos = ((Tile)currTile).getPos();
				//System.out.println(pos.toString());
				//System.out.println(cam.camToScreen(pos));
			tile.draw(cam.camToScreen(pos));
		}
	}
	
}
